package ar.edu.sccs.util;

import java.io.BufferedReader;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.List;

import ar.edu.sccs.model.loader.dto.DataClazz;
import ar.edu.sccs.monitoring.exception.SccsGenericException;

public class ObjectInStream {
	private ObjectInputStream file2read;

	public static List<String> getContents(File aFile) {
		// ...checks on aFile are elided
		List<String >contents = new ArrayList<String>();

		try {
			// use buffering, reading one line at a time
			// FileReader always assumes default encoding is OK!
			BufferedReader input = new BufferedReader(new FileReader(aFile));
			try {
				String line = null; // not declared within while loop
				/*
				 * readLine is a bit quirky : it returns the content of a line
				 * MINUS the newline. it returns null only for the END of the
				 * stream. it returns an empty String if two newlines appear in
				 * a row.
				 */
				while ((line = input.readLine()) != null) {
					contents.add(line);
				}
			} finally {
				input.close();
			}
		} catch (IOException ex) {
			ex.printStackTrace();
		}

		return contents;
	}

	public List<DataClazz> readDataClazzFile(String filePath) throws SccsGenericException {
		List<DataClazz> dataClazz = new ArrayList<DataClazz>();

		try {
			openFile(filePath);
		} catch (Exception e1) {
			throw new SccsGenericException(e1);
		}

		while (true) {
			try {
				dataClazz.add((DataClazz) file2read.readObject());
			} catch (EOFException eofe) {
				break;
			} catch (Exception e2) {
				throw new SccsGenericException(e2);
			}
		}

		closeFile();
		return dataClazz;
	}

	private void openFile(String filePath) throws Exception {
		file2read = new ObjectInputStream(new FileInputStream(new File(filePath)));
	}

	private void closeFile() {
		try {
			file2read.close();
		} catch (Exception e) {
		}
	}
}
